package com.school.sports.config;

import com.school.sports.filter.JwtAuthenticationFilter;
import com.school.sports.service.Impl.UserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Spring Security 配置类
 */
@Slf4j
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    private final UserDetailsServiceImpl userDetailsService;
    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    public SecurityConfig(UserDetailsServiceImpl userDetailsService,
                        JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.userDetailsService = userDetailsService;
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    /**
     * 认证提供者
     */
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    /**
     * CORS配置 - 安全加固版本
     * 限制允许的来源域名，提高系统安全性
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 限制允许的来源域名，仅允许本地开发环境访问
        configuration.setAllowedOrigins(Arrays.asList(
            "http://localhost:8083",
            "http://localhost:8084",
            "http://127.0.0.1:8083",
            "http://127.0.0.1:8084",
            "http://localhost:8080",  // 添加常用的前端开发端口
            "http://127.0.0.1:8080"
        ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF（使用JWT时不需要）
            .csrf().disable()

            // 启用CORS
            .cors().configurationSource(corsConfigurationSource())

            .and()

            // 配置会话管理为无状态
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

            .and()

            // 配置授权规则
            .authorizeRequests()
                // 允许匿名访问的端点 - 由于设置了context-path，路径不需要加/api前缀
                .antMatchers("/auth/login").permitAll()
                .antMatchers("/auth/validate").permitAll()
                .antMatchers("/auth/check-username").permitAll()
                .antMatchers("/auth/register").permitAll()
                .antMatchers("/auth/verify-security-question").permitAll()
                .antMatchers("/auth/reset-password").permitAll()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/error").permitAll()
                .antMatchers("/favicon.ico").permitAll()

                // 静态资源
                .antMatchers("/static/**", "/css/**", "/js/**", "/images/**").permitAll()

                // 管理员权限
                .antMatchers("/admin/**").hasRole("管理员")

                // 老师权限
                .antMatchers("/teacher/**").hasAnyRole("管理员", "老师")

                // 裁判权限
                .antMatchers("/referee/**").hasAnyRole("管理员", "老师", "裁判")

                // 其他请求需要认证
                .anyRequest().authenticated()

            .and()

            // 配置认证提供者
            .authenticationProvider(authenticationProvider())

            // 添加JWT过滤器
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}